<template>
  <div class="container mx-auto px-4 py-8">
    <div class="flex flex-col lg:flex-row gap-8">
      <!-- 侧边栏 -->
      <div class="lg:w-64 flex-shrink-0">
        <div class="bg-white rounded-lg shadow-sm p-6">
          <!-- 用户信息概览 -->
          <div class="text-center mb-6">
            <el-avatar :size="80" :src="userInfo.avatar" />
            <h3 class="mt-4 text-lg font-semibold">{{ userInfo.nickname || userInfo.username }}</h3>
            <div v-if="userInfo.gender || userInfo.age" class="flex justify-center items-center gap-2 mt-2 text-sm text-gray-500">
              <span v-if="userInfo.gender">{{ userInfo.gender === 1 ? '男' : userInfo.gender === 2 ? '女' : '' }}</span>
              <span v-if="userInfo.age">{{ userInfo.age }}岁</span>
            </div>
            <p v-if="userInfo.school" class="text-gray-500 text-sm mt-1">{{ userInfo.school }}</p>
            <p v-if="userInfo.major" class="text-gray-500 text-sm">{{ userInfo.major }}</p>
            <p v-if="userInfo.grade" class="text-gray-500 text-sm">{{ userInfo.grade }}</p>
          </div>

          <!-- 导航菜单 -->
          <el-menu
            :default-active="activeMenu"
            class="border-none"
            @select="handleMenuSelect"
          >
            <el-menu-item index="info">
              <el-icon><User /></el-icon>
              <span>个人信息</span>
            </el-menu-item>
            <el-menu-item index="security">
              <el-icon><Key /></el-icon>
              <span>账号安全</span>
            </el-menu-item>
            <el-menu-item index="comments">
              <el-icon><ChatRound /></el-icon>
              <span>我的评论</span>
            </el-menu-item>
            <el-menu-item index="replies">
              <el-icon><ChatDotRound /></el-icon>
              <span>评论回复</span>
            </el-menu-item>
          </el-menu>
        </div>
      </div>

      <!-- 主要内容区域 -->
      <div class="flex-grow">
        <!-- 个人信息 -->
        <div v-if="activeMenu === 'info'" class="bg-white rounded-lg shadow-sm p-6">
          <h2 class="text-xl font-semibold mb-6">个人信息</h2>
          <el-form
            ref="formRef"
            :model="userForm"
            :rules="formRules"
            label-width="100px"
          >
            <el-form-item label="头像">
              <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :auto-upload="false"
                :on-change="handleAvatarChange"
              >
                <img v-if="userForm.avatar" :src="userForm.avatar" class="w-24 h-24 rounded-full object-cover" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
            <el-form-item v-if="userInfo.username" label="用户名">
              <el-input v-model="userForm.username" disabled />
            </el-form-item>
            <el-form-item v-if="userInfo.nickname !== undefined" label="昵称" prop="nickname">
              <el-input v-model="userForm.nickname" />
            </el-form-item>
            <el-form-item v-if="userInfo.realname !== undefined" label="真实姓名" prop="realname">
              <el-input v-model="userForm.realname" />
            </el-form-item>
            <el-form-item v-if="userInfo.gender !== undefined" label="性别">
              <el-radio-group v-model="userForm.gender">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="userInfo.age !== undefined" label="年龄">
              <el-input-number v-model="userForm.age" :min="1" :max="120" />
            </el-form-item>
            <el-form-item v-if="userInfo.school !== undefined" label="学校" prop="school">
              <el-input v-model="userForm.school" />
            </el-form-item>
            <el-form-item v-if="userInfo.major !== undefined" label="专业" prop="major">
              <el-input v-model="userForm.major" />
            </el-form-item>
            <el-form-item v-if="userInfo.grade !== undefined" label="年级">
              <el-select v-model="userForm.grade" placeholder="请选择年级">
                <el-option label="大一" value="大一"></el-option>
                <el-option label="大二" value="大二"></el-option>
                <el-option label="大三" value="大三"></el-option>
                <el-option label="大四" value="大四"></el-option>
                <el-option label="研一" value="研一"></el-option>
                <el-option label="研二" value="研二"></el-option>
                <el-option label="研三" value="研三"></el-option>
                <el-option label="博士" value="博士"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="userInfo.email !== undefined" label="邮箱" prop="email">
              <el-input v-model="userForm.email" />
            </el-form-item>
            <el-form-item v-if="userInfo.phone !== undefined" label="手机" prop="phone">
              <el-input v-model="userForm.phone" />
            </el-form-item>
            <el-form-item v-if="userInfo.bio !== undefined" label="个人简介" prop="bio">
              <el-input type="textarea" v-model="userForm.bio" :rows="4" placeholder="介绍一下自己..." />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSaveInfo">保存修改</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        
        <!-- 账号安全 -->
        <div v-else-if="activeMenu === 'security'" class="bg-white rounded-lg shadow-sm p-6">
          <h2 class="text-xl font-semibold mb-6">账号安全</h2>
          <el-form
            ref="passwordFormRef"
            :model="passwordForm"
            :rules="passwordRules"
            label-width="120px"
          >
            <el-form-item label="当前密码" prop="oldPassword">
              <el-input 
                v-model="passwordForm.oldPassword" 
                type="password" 
                show-password
                placeholder="请输入当前密码" 
              />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input 
                v-model="passwordForm.newPassword" 
                type="password" 
                show-password
                placeholder="请输入新密码" 
              />
            </el-form-item>
            <el-form-item label="确认新密码" prop="confirmNewPassword">
              <el-input 
                v-model="passwordForm.confirmNewPassword" 
                type="password" 
                show-password
                placeholder="请再次输入新密码" 
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleUpdatePassword" :loading="passwordUpdating">更新密码</el-button>
            </el-form-item>
          </el-form>
          
          <div class="mt-8 pt-6 border-t border-gray-200">
            <h3 class="text-lg font-semibold mb-4">账号绑定</h3>
            <div class="space-y-4">
              <div class="flex justify-between items-center">
                <div class="flex items-center gap-3">
                  <el-icon class="text-blue-500"><Message /></el-icon>
                  <div>
                    <div class="font-medium">邮箱绑定</div>
                    <div class="text-gray-500 text-sm">{{ userInfo.email || '暂未绑定邮箱' }}</div>
                  </div>
                </div>
                <el-button type="primary" link>{{ userInfo.email ? '修改' : '绑定' }}</el-button>
              </div>
              
              <div class="flex justify-between items-center">
                <div class="flex items-center gap-3">
                  <el-icon class="text-green-500"><Iphone /></el-icon>
                  <div>
                    <div class="font-medium">手机绑定</div>
                    <div class="text-gray-500 text-sm">{{ userInfo.phone ? '已绑定手机：' + maskPhone(userInfo.phone) : '暂未绑定手机' }}</div>
                  </div>
                </div>
                <el-button type="primary" link>{{ userInfo.phone ? '修改' : '绑定' }}</el-button>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 我的评论 -->
        <div v-else-if="activeMenu === 'comments'" class="bg-white rounded-lg shadow-sm p-6">
          <div class="flex justify-between items-center mb-6">
            <h2 class="text-xl font-semibold">我的评论</h2>
            <el-button :loading="userStore.commentsLoading" @click="loadUserComments" type="primary" plain>
              <el-icon><Refresh /></el-icon> 刷新
            </el-button>
          </div>
          
          <div v-if="userStore.commentsLoading" class="py-10 text-center">
            <el-icon class="is-loading text-2xl text-gray-400"><Loading /></el-icon>
            <p class="mt-2 text-gray-500">加载中...</p>
          </div>
          
          <div v-else-if="userStore.myComments.length === 0" class="py-10 text-center">
            <el-empty description="暂无评论" />
          </div>
          
          <div v-else>
            <div class="space-y-4">
              <div 
                v-for="(comment, index) in paginatedComments" 
                :key="index" 
                class="p-4 border rounded-lg hover:bg-gray-50"
              >
                <div class="flex justify-between items-start mb-2">
                  <div>
                    <h4 class="font-semibold mb-2">评论于：{{ comment.postTitle }}</h4>
                    <p class="text-gray-600">{{ comment.content }}</p>
                  </div>
                  <el-button type="danger" text @click="handleDeleteComment(comment.id)">删除</el-button>
                </div>
                <div class="text-sm text-gray-500">
                  {{ comment.createTime }}
                </div>
              </div>
            </div>
            
            <!-- 分页 -->
            <div class="flex justify-center mt-6" v-if="userStore.myComments.length > commentsPagination.pageSize">
              <el-pagination
                v-model:current-page="commentsPagination.currentPage"
                :page-size="commentsPagination.pageSize"
                :total="userStore.myComments.length"
                layout="prev, pager, next"
                @current-change="handleCommentsPageChange"
              />
            </div>
          </div>
        </div>
        
        <!-- 评论回复 -->
        <div v-else-if="activeMenu === 'replies'" class="bg-white rounded-lg shadow-sm p-6">
          <div class="flex justify-between items-center mb-6">
            <h2 class="text-xl font-semibold">评论回复</h2>
            <el-button :loading="userStore.repliesLoading" @click="loadCommentReplies" type="primary" plain>
              <el-icon><Refresh /></el-icon> 刷新
            </el-button>
          </div>
          
          <div v-if="userStore.repliesLoading" class="py-10 text-center">
            <el-icon class="is-loading text-2xl text-gray-400"><Loading /></el-icon>
            <p class="mt-2 text-gray-500">加载中...</p>
          </div>
          
          <div v-else-if="userStore.commentReplies.length === 0" class="py-10 text-center">
            <el-empty description="暂无回复" />
          </div>
          
          <div v-else>
            <div class="space-y-4">
              <div 
                v-for="(reply, index) in paginatedReplies" 
                :key="index" 
                class="p-4 border rounded-lg hover:bg-gray-50"
              >
                <div class="mb-4">
                  <div class="flex items-center gap-2 mb-2">
                    <el-avatar :size="24" :src="reply.author.avatar" />
                    <span class="font-semibold">{{ reply.author.name }}</span>
                    <span class="text-gray-500">回复了你的评论</span>
                  </div>
                  <p class="text-gray-600">{{ reply.content }}</p>
                </div>
                <div class="text-sm text-gray-500">
                  {{ reply.createTime }}
                </div>
              </div>
            </div>
            
            <!-- 分页 -->
            <div class="flex justify-center mt-6" v-if="userStore.commentReplies.length > repliesPagination.pageSize">
              <el-pagination
                v-model:current-page="repliesPagination.currentPage"
                :page-size="repliesPagination.pageSize"
                :total="userStore.commentReplies.length"
                layout="prev, pager, next"
                @current-change="handleRepliesPageChange"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  User,
  ChatRound,
  ChatDotRound,
  Plus,
  Loading,
  Refresh,
  Key,
  Message,
  Iphone
} from '@element-plus/icons-vue'

// 获取用户store
const userStore = useUserStore()
const router = useRouter()

// 当前选中的菜单
const activeMenu = ref('info')

// 用户信息，从store中获取
const userInfo = computed(() => userStore.getUserProfile)

// 表单数据，克隆用户信息到表单
const userForm = ref({
  nickname: '',
  realname: '',
  avatar: '',
  school: '',
  major: '',
  grade: '',
  bio: '',
  gender: 1,
  age: 20,
  email: '',
  phone: ''
})

// 密码表单
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmNewPassword: ''
})

// 密码更新状态
const passwordUpdating = ref(false)

// 我的评论分页
const commentsPagination = ref({
  currentPage: 1,
  pageSize: 5
})

// 我的回复分页
const repliesPagination = ref({
  currentPage: 1,
  pageSize: 5
})

// 表单引用
const formRef = ref(null)
const passwordFormRef = ref(null)

// 分页后的评论列表
const paginatedComments = computed(() => {
  const startIndex = (commentsPagination.value.currentPage - 1) * commentsPagination.value.pageSize
  const endIndex = startIndex + commentsPagination.value.pageSize
  return userStore.myComments.slice(startIndex, endIndex)
})

// 分页后的回复列表
const paginatedReplies = computed(() => {
  const startIndex = (repliesPagination.value.currentPage - 1) * repliesPagination.value.pageSize
  const endIndex = startIndex + repliesPagination.value.pageSize
  return userStore.commentReplies.slice(startIndex, endIndex)
})

// 手机号码遮掩函数
const maskPhone = (phone) => {
  if (!phone || phone.length !== 11) return phone
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

// 初始化用户表单
const initUserForm = () => {
  const info = userStore.getUserProfile
  userForm.value = {
    username: info.username || '',
    nickname: info.nickname || '',
    realname: info.realname || '',
    avatar: info.avatar || '',
    school: info.school || '',
    major: info.major || '',
    grade: info.grade || '',
    gender: info.gender || 0,
    age: info.age || '',
    email: info.email || '',
    phone: info.phone || '',
    bio: info.bio || ''
  }
}

// 重置表单
const resetForm = () => {
  initUserForm()
  ElMessage.info('表单已重置')
}

// 表单校验规则
const formRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  school: [
    { required: true, message: '请输入学校', trigger: 'blur' }
  ],
  email: [
    { pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: '请输入有效的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
  ],
  bio: [
    { max: 200, message: '个人简介不能超过200个字符', trigger: 'blur' }
  ]
}

// 密码校验规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为6个字符', trigger: 'blur' }
  ],
  confirmNewPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ]
}

// 处理菜单选择
const handleMenuSelect = async (key) => {
  activeMenu.value = key
  
  if (key === 'comments') {
    await loadUserComments()
  } else if (key === 'replies') {
    await loadCommentReplies()
  }
}

// 加载用户评论
const loadUserComments = async () => {
  try {
    if (!userStore.isLoggedIn) {
      ElMessage.warning('请先登录后查看我的评论')
      activeMenu.value = 'info'
      return
    }
    
    await userStore.fetchMyComments()
    
    // 重置到第一页
    commentsPagination.value.currentPage = 1
  } catch (error) {
    console.error('加载用户评论出错:', error)
    ElMessage.error('获取评论失败')
  }
}

// 加载评论回复
const loadCommentReplies = async () => {
  try {
    if (!userStore.isLoggedIn) {
      ElMessage.warning('请先登录后查看评论回复')
      activeMenu.value = 'info'
      return
    }
    
    await userStore.fetchCommentReplies()
    
    // 重置到第一页
    repliesPagination.value.currentPage = 1
  } catch (error) {
    console.error('加载评论回复出错:', error)
    ElMessage.error('获取评论回复失败')
  }
}

// 处理头像更改
const handleAvatarChange = (file) => {
  // TODO: 处理头像上传到服务器，目前仅做本地预览
  userForm.value.avatar = URL.createObjectURL(file.raw)
}

// 处理保存个人信息
const handleSaveInfo = async () => {
  try {
    // 表单验证
    await formRef.value.validate()

    // 构建用于更新的数据对象
    const updateData = {}
    
    // 只包含有值的字段
    if (userForm.value.nickname) updateData.nickname = userForm.value.nickname
    if (userForm.value.realname) updateData.realname = userForm.value.realname
    if (userForm.value.avatar) updateData.avatar = userForm.value.avatar
    if (userForm.value.school !== undefined) updateData.school = userForm.value.school
    if (userForm.value.major !== undefined) updateData.major = userForm.value.major
    if (userForm.value.grade !== undefined) updateData.grade = userForm.value.grade
    if (userForm.value.gender !== undefined) updateData.gender = userForm.value.gender
    if (userForm.value.age !== undefined) updateData.age = userForm.value.age
    if (userForm.value.email) updateData.email = userForm.value.email
    if (userForm.value.phone) updateData.phone = userForm.value.phone
    if (userForm.value.bio !== undefined) updateData.bio = userForm.value.bio
    
    // 调用store的更新方法，使用新的API
    const success = await userStore.updateUserInfo(updateData)
    
    if (success) {
      ElMessage.success('信息更新成功')
    } else {
      ElMessage.error('信息更新失败')
    }
  } catch (error) {
    console.error('表单验证或保存出错:', error)
    ElMessage.error('保存失败:' + (error.message || '未知错误'))
  }
}

// 处理密码更新
const handleUpdatePassword = async () => {
  try {
    // 表单验证
    await passwordFormRef.value.validate()

    passwordUpdating.value = true
    const success = await userStore.changePassword({
      oldPassword: passwordForm.value.oldPassword,
      newPassword: passwordForm.value.newPassword
    })
    
    if (success) {
      ElMessage.success('密码修改成功，请重新登录')
      // 清除表单
      passwordForm.value = {
        oldPassword: '',
        newPassword: '',
        confirmNewPassword: ''
      }
      // 退出登录，重定向到登录页
      setTimeout(() => {
        userStore.logout()
      }, 1500)
    } else {
      ElMessage.error('密码修改失败，请检查当前密码是否正确')
    }
  } catch (error) {
    console.error('密码更新出错:', error)
    ElMessage.error('密码修改失败: ' + (error.message || '未知错误'))
  } finally {
    passwordUpdating.value = false
  }
}

// 处理删除评论
const handleDeleteComment = (commentId) => {
  ElMessageBox.confirm('确认删除这条评论吗？此操作不可撤销。', '确认删除', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // TODO: 调用删除评论API
    ElMessage.success('删除成功')
    loadUserComments() // 重新加载评论列表
  }).catch(() => {})
}

// 处理评论分页变化
const handleCommentsPageChange = (page) => {
  commentsPagination.value.currentPage = page
}

// 处理回复分页变化
const handleRepliesPageChange = (page) => {
  repliesPagination.value.currentPage = page
}

// 组件挂载时初始化数据
onMounted(async () => {
  // 确保用户已登录，否则获取用户信息
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录查看个人资料')
    router.push('/auth/login')
    return
  }
  
  // 如果已登录但没有用户信息，尝试获取
  if (!userStore.userInfo) {
    try {
      const success = await userStore.fetchUserInfo()
      if (!success) {
        ElMessage.warning('获取用户信息失败，请重新登录')
        router.push('/auth/login')
        return
      }
    } catch (error) {
      console.error('获取用户信息错误:', error)
      ElMessage.error('获取用户信息失败')
      router.push('/auth/login')
      return
    }
  }
  
  // 初始化表单数据
  initUserForm()
  
  // 只在登录情况下才加载初始选项卡数据
  if (userStore.isLoggedIn) {
    if (activeMenu.value === 'comments') {
      await loadUserComments()
    } else if (activeMenu.value === 'replies') {
      await loadCommentReplies()
    }
  }
})
</script>

<style scoped>
.avatar-uploader {
  display: flex;
  justify-content: center;
}

.avatar-uploader :deep(.el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 96px;
  height: 96px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style> 